package com.jeesite.modules.exam.socreResult.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.annotation.RepeatSubmit;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.assessment.service.DcSupExamInfoService;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuotaAdd;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.score.entity.DcSupExamSumScore;
import com.jeesite.modules.exam.score.service.DcSupExamSumScoreService;
import com.jeesite.modules.exam.socreResult.dto.CheckIndexDataDto;
import com.jeesite.modules.exam.socreResult.dto.ExamUnitNameDto;
import com.jeesite.modules.exam.socreResult.dto.GradingAndResultsDto;
import com.jeesite.modules.exam.socreResult.dto.ResultCheckDataDto;
import com.jeesite.modules.exam.socreResult.entity.DcSupExamGroup;
import com.jeesite.modules.exam.socreResult.entity.DcSupExamGroupUnit;
import com.jeesite.modules.exam.socreResult.entity.DcSupExamOrgSelect;
import com.jeesite.modules.exam.socreResult.service.DcSupExamGroupUnitService;
import com.jeesite.modules.exam.socreResult.service.DcSupExamOrgSelectService;
import com.jeesite.modules.exam.socreResult.service.DcSupExamSumScoreResultService;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.modules.task.taskgroup.entity.DcSupTaskGroup;
import com.jeesite.modules.task.taskgroup.entity.DcSupTaskGroupUnit;
import com.jeesite.modules.task.taskgroup.service.DcSupTaskGroupService;
import com.jeesite.modules.task.taskgroup.service.DcSupTaskGroupUnitService;
import com.jeesite.modules.utils.OfficeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 评分模块相关接口
 *
 * @author wangjie
 * @date 2022-05-31
 */
@Api("评分结果")
@RequestMapping("${adminPath}/exam/dcSupExamSumScoreResult")
@Controller
public class DcSupExamSumScoreResultController extends BaseController {

    @Autowired
    private DcSupExamSumScoreResultService dcSupExamSumScoreResultService;
    @Autowired
    private DcSupExamInfoService dcSupExamInfoService;

    @Autowired
    private DcSupExamOrgSelectService dcSupExamOrgSelectService;
    @Autowired
    DcSupExamGroupUnitService dcSupExamGroupUnitService;

    @Autowired
    private DcSupExamSumScoreService dcSupExamSumScoreService;

    @ApiModelProperty("评分结果首页")
    @RequestMapping("index")
    public String index(Model model) {
        model.addAttribute("yearList", OfficeUtil.getYearList(null));
        return "modules/exam/scoresResult/gradingAndResults";
    }
    @ApiModelProperty("单项评分排名自查")
    @RequestMapping("indexPerson")
    public String indexPerson(Model model) {
        model.addAttribute("yearList", OfficeUtil.getYearList(null));
        return "modules/exam/scoresResult/gradingAndResultsPerson";
    }

    @ApiModelProperty("评分首页数据列表查询")
    @RequestMapping("listData")
    @ResponseBody
    public Page<DcSupExamInfo> listData(DcSupExamInfo dcSupExamInfo, HttpServletRequest request, HttpServletResponse response) {
//        dcSupExamInfo.setPage(new Page<>(request, response));
//        return dcSupExamSumScoreResultService.listData(dcSupExamInfo);
        dcSupExamInfo.setPage(new Page<>(request, response));
        Page<DcSupExamInfo> page = dcSupExamInfoService.findPage(dcSupExamInfo);
        return page;
    }

    /**
     * 考核自评查看
     *
     * @param model
     * @return
     */
    @ApiModelProperty("考核自评查看")
    @RequestMapping("checkIndex")
    public String checkIndex(Model model, String examId, String year) {
        checkParam(examId,year);
        // 查询考核自评数据信息
        Map<String, String> examSumScore = new HashMap<>();
        examSumScore.put("examId", examId);
        examSumScore.put("year", year);
        model.addAttribute("examSumScore", examSumScore);
        return "modules/exam/scoresResult/checkIndexLeft";
    }

    @ApiModelProperty("考核自评查看--数据")
    @RequestMapping("checkIndexData")
    public String checkIndexData(String examId, String year, String orgCode, HttpServletRequest request, HttpServletResponse response,Model model) {
        checkParam(examId,orgCode,year);
        Page<CheckIndexDataDto> checkIndexDataDtoPage = dcSupExamSumScoreResultService.checkIndexData(examId, year, orgCode, request, response);
        Map<String, String> checkInfo = dcSupExamSumScoreResultService.checkInfo(examId, year, orgCode);
        if (checkInfo !=null){
            model.addAttribute("noticeEndTime",checkInfo.get("noticeendtime"));
            model.addAttribute("contactName",checkInfo.get("contactname"));
            model.addAttribute("contactPhone",checkInfo.get("contactphone"));
            model.addAttribute("id",checkInfo.get("id"));
        }else{
            checkInfo = new HashMap<>();
            model.addAttribute("noticeEndTime",null);
            model.addAttribute("contactName",null);
            model.addAttribute("contactPhone",null);
            model.addAttribute("id",null);
        }
        model.addAttribute("examSumScore",checkInfo);
        model.addAttribute("checkIndexDataDtoPage",checkIndexDataDtoPage.getList());
        return "modules/exam/scoresResult/checkIndexRight";
    }

    /**
     * 考核结果查看
     *
     * @param model
     * @return
     */
    @ApiModelProperty("考核结果查看")
    @RequestMapping("resultCheck")
    public String resultCheck(Model model, String examId, String year) {
        Map<String, String> examSumScore = new HashMap<>();
        examSumScore.put("examId", examId);
        examSumScore.put("year", year);
        model.addAttribute("examSumScore", examSumScore);
        return "modules/exam/scoresResult/resultCheckLeft";
    }

    /**
     * 查看考核数据信息
     *
     * @param orgCode  被考核单位编码
     * @param examId   考核任务id
     * @param year     考核年份
     * @param request
     * @param response
     * @return
     */
    @ApiModelProperty("考核结果数据")
    @RequestMapping("resultCheckData")
    public String resultCheckData(Model model, String orgCode, String examId, String year, String version, HttpServletRequest request, HttpServletResponse response) {
        checkParam(examId,orgCode,year);
        List<DcSupExamSumQuotaInfo> result = dcSupExamSumScoreResultService.queryExamSumScore(examId,null, orgCode,"single");
        List<DcSupExamQuotaAdd> dcSupExamQuotaAdds=dcSupExamSumScoreResultService.queryExamSumScore(examId,null, orgCode,"addAndSub");
        model.addAttribute("checkIndexDataDtoPage",result);
        model.addAttribute("addAndSub",dcSupExamQuotaAdds);
        model.addAttribute("examId",examId);
        return "modules/exam/scoresResult/resultCheckRight";
    }

    /**
     * @param examId   考核id
     * @param unitName 考核单位名称
     * @param request
     * @param response
     * @return
     */
    @ApiModelProperty("考核单位列表")
    @RequestMapping("unitList")
    @ResponseBody
    public Page<ExamUnitNameDto> unitList(String examId, String unitName,String type, HttpServletRequest request, HttpServletResponse response) {
        Page<ExamUnitNameDto> result = dcSupExamSumScoreResultService.queryUnits(examId, unitName,type, request, response);
        return result;
    }


    @ApiModelProperty("文件导出")
    @RequestMapping("export")
    public void export(String examId, String orgCode, String year, HttpServletRequest request, HttpServletResponse response) throws IOException {
        dcSupExamSumScoreResultService.export(examId, request, response);
    }

    /**
     * 参数校验
     *
     * @param param
     */
    private void checkParam(String... param) {
        for (int i = 0; i < param.length; i++) {
            if (StringUtils.isEmpty(param[i])) {
                throw new RuntimeException("参数不能为空");
            }
        }
    }

    /**
     * 常用列表主页
     * @param dcSupTaskGroup
     * @param model
     * @return
     */
    @RequestMapping(value = {"examGroupList", ""})
    public String list(DcSupExamGroup dcSupTaskGroup, Model model) {
        model.addAttribute("dcSupTaskGroup", dcSupTaskGroup);
        dcSupTaskGroup.setCreateBy(UserUtils.getUser().getUserCode());
        List<DcSupExamGroup> list = dcSupExamOrgSelectService.queryGroup(dcSupTaskGroup);
        model.addAttribute("assessmentUnit", list);
        return "modules/exam/scoresResult/dcSupExamGroupIndex";
    }


    /**
     * 常用列表
     * @param dcSupTaskGroup
     * @param
     * @return
     */
    @RequestMapping("listGroup")
    @ResponseBody
    public Object listGroup(DcSupExamGroup dcSupTaskGroup) {
        dcSupTaskGroup.setCreateBy(UserUtils.getUser().getUserCode());
        List<DcSupExamGroup> list = dcSupExamOrgSelectService.queryGroup(dcSupTaskGroup);

        return list;
    }

    @RequestMapping(value = "radio")
    @ResponseBody
    public DcSupExamGroupUnit radio(DcSupExamGroupUnit dcSupTaskGroupUnit) {
        List<String> orgs = new ArrayList<>();
        List<String> orgNames = new ArrayList<>();
        if(com.jeesite.common.lang.StringUtils.isNotBlank(dcSupTaskGroupUnit.getGroupId())){
            List<DcSupExamGroupUnit> list = dcSupExamGroupUnitService.findList(dcSupTaskGroupUnit);
            list.forEach(
                    unit -> {
                        orgs.add(unit.getUnitCode());
                        orgNames.add(unit.getUnitName());
                    }
            );
            dcSupTaskGroupUnit.setUnitCodes(com.jeesite.common.lang.StringUtils.join(orgs,","));
            dcSupTaskGroupUnit.setUnitNames(com.jeesite.common.lang.StringUtils.join(orgNames,","));
        }
        return dcSupTaskGroupUnit;
    }

    /**
     * 查询常用组列表数据
     */
    @RequestMapping(value = {"groupList", ""})
    public String groupList(DcSupExamGroupUnit dcSupTaskGroupUnit, Model model) {
        model.addAttribute("dcSupExamGroupUnit", dcSupTaskGroupUnit);
        return "modules/exam/scoresResult/dcSupExamGroupUnitList";
    }

    /**
     * 常用组里选择的数据列表信息
     */
    @RequestMapping(value = "groupListData")
    @ResponseBody
    public Page<DcSupExamGroupUnit> groupListData(Model model,DcSupExamGroupUnit dcSupTaskGroupUnit, HttpServletRequest request, HttpServletResponse response) {
        Page<DcSupExamGroupUnit> page = new Page<>(request, response);
        page.setPageSize(20000);
        dcSupTaskGroupUnit.setPage(page);
        page = dcSupExamOrgSelectService.groupListData(dcSupTaskGroupUnit);
        return page;
    }

    /**
     *
     * 添加常用组名称弹框
     */
    @RequestMapping(value = "form")
    public String form(DcSupExamGroup dcSupTaskGroup, Model model) {
        model.addAttribute("dcSupExamGroup", dcSupTaskGroup);
        return "modules/exam/scoresResult/dcSupExamGroupForm";
    }
    /**
     * 新建常用组保存按钮
     */

    @PostMapping(value = "saveOrgGroup")
    @RepeatSubmit
    @ResponseBody
    public String saveOrgGroup(@Validated DcSupExamGroup dcSupTaskGroup) {
        dcSupTaskGroup.setCreateBy(UserUtils.getUser().getUserCode());
        dcSupExamOrgSelectService.saveOrg(dcSupTaskGroup);
        return renderResult(Global.TRUE, text("保存成功！"));
    }

    /**
     * 删常用组数据信息
     */
    @RequestMapping(value = "deleteGroup")
    @ResponseBody
    public String deleteGroup(DcSupExamGroup dcSupExamGroup) {
        dcSupExamOrgSelectService.deleteGroup(dcSupExamGroup);
        return renderResult(Global.TRUE, text("删除机构成功！"));
    }


    /**
     * 机构列表数据信息
     */
    @RequestMapping(value = "orgSelect")
    @ResponseBody
    public Page<DcSupExamOrgSelect> orgSelect(Model model, DcSupExamOrgSelect dcSupExamOrgSelect, HttpServletRequest request, HttpServletResponse response) {
        Page<DcSupExamOrgSelect> page = new Page<>(request, response);
        page.setPageSize(20000);
        dcSupExamOrgSelect.setPage(page);
        dcSupExamOrgSelect.setOrgStatus("0");
        page = dcSupExamOrgSelectService.findPage(dcSupExamOrgSelect);
        return page;
    }

    /**
     * 机构列表查询弹框
     * @param type 不传type 则前端页面展示 市直和区县  1 为区县 2 为市直
     * @param isGroupOptions  是否是常用组选择  是 传1  否传 0
     */
    @RequestMapping(value = "orgForm")
    public String orgForm(DcSupExamGroupUnit dcSupExamGroupUnit,Model model, String type,String isGroupOptions) {
        model.addAttribute("dcSupExamGroupUnit", dcSupExamGroupUnit);
        // 区县、市直单位选择
        model.addAttribute("type",type);
        model.addAttribute("isGroupOptions",isGroupOptions);
        return "modules/exam/scoresResult/dcSupExamGroupUnitForm";
    }


    /**
     * 选择机构后保存数据信息到常用组中
     */
    @PostMapping(value = "saveGroupOrg")
    @ResponseBody
    public String saveGroupOrg( String dcSupTaskGroupUnit,String groupId) {
        dcSupExamOrgSelectService.saveExamGroupUnit(dcSupTaskGroupUnit,groupId);
        return renderResult(Global.TRUE, text("保存成功！"));
    }


    /**
     * 删常用组内的组织机构信息
     */
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(DcSupExamGroupUnit dcSupTaskGroupUnit) {
        dcSupExamOrgSelectService.deleteGroupUnit(dcSupTaskGroupUnit);
        return renderResult(Global.TRUE, text("删除机构成功！"));
    }

    /**
     * 选择机构后保存数据信息到常用组中
     */
    @PostMapping(value = "saveOrg")
    @ResponseBody
    public String saveOrg(DcSupExamOrgSelect dcSupExamOrgSelect) {
        //{"unitNames":"芜湖市政府,市政协机关及民主党派、工商联,无为市,湾沚区","groupId":"1548136498841608192","unitCodes":"14,2,17,3","isNewRecord":true}
        dcSupExamOrgSelectService.saveOrgByAllOrg(dcSupExamOrgSelect);
        return renderResult(Global.TRUE, text("保存成功！"));
    }
}
